package com.weasel.weixin.mp.servlet;

import com.weasel.weixin.commons.accounts.Oauth2AccessTokenRequest;
import com.weasel.weixin.commons.accounts.Oauth2AccessTokenResponse;
import com.weasel.weixin.mp.builder.MpConfigBuilder;
import com.weasel.weixin.mp.config.MpConfig;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Dylan on 2015/9/28.
 */
public class RefreshOauth2AccessTokenServlet extends WeixinBaseServlet {



    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MpConfig config = MpConfigBuilder.fromXML("classpath:weixin-config.xml");

        Oauth2AccessTokenResponse accessTokenResponse = Oauth2AccessTokenServlet.cache.getIfPresent("oauth2_access_token");
        if(null == accessTokenResponse){
            response.getWriter().write("用户还没授权，请先授权");
            return;
        }
        accessTokenResponse = new Oauth2AccessTokenRequest(config).refreshOauth2AccessToken(accessTokenResponse.getRefreshToken());
        Oauth2AccessTokenServlet.cache.put("oauth2_access_token", accessTokenResponse);

        System.out.print("access_token:" + accessTokenResponse.getAccessToken() + " refresh_token:" + accessTokenResponse.getRefreshToken());
        response.getWriter().write("刷新授权成功");
    }
}
